package org.mikhaylov.cp.service.command.impl;

import javax.servlet.http.HttpServletRequest;

import org.mikhaylov.cp.service.command.ServiceCommand;
import org.mikhaylov.cp.service.db.entities.City;
import org.mikhaylov.cp.service.db.entities.User;
import org.mikhaylov.cp.service.hibernate.HibernateManager;
import org.mikhaylov.cp.service.response.ResponseType;

public class UpdateProfileServiceCommand extends ServiceCommand {

	private static final long serialVersionUID = 1267771752369212254L;

	private User user = null;
	private String name = null;
	private String phone = null;
	private String desc = null;
	private City city = null;

	@Override
	protected boolean checkParams(HttpServletRequest request) {
		if (request.getAttribute("user") == null
				|| !(request.getAttribute("user") instanceof User)
				|| request.getAttribute("name") == null
				|| !(request.getAttribute("name") instanceof String)
				|| request.getAttribute("phone") == null
				|| !(request.getAttribute("phone") instanceof String)
				|| request.getAttribute("desc") == null
				|| !(request.getAttribute("desc") instanceof String)
				|| request.getAttribute("city") == null
				|| !(request.getAttribute("city") instanceof String)) {
			response.setType(ResponseType.ERROR);
			response.setMeta("Bad parameters");
			return false;
		}
		return true;
	}

	@Override
	protected boolean extractParams(HttpServletRequest request) {
		user = (User) request.getAttribute("user");
		name = (String) request.getAttribute("name");
		phone = (String) request.getAttribute("phone");
		desc = (String) request.getAttribute("desc");
		city = HibernateManager.getInstance().getCity(
				String.valueOf(request.getAttribute("city")));
		return true;
	}

	@Override
	protected void process(HttpServletRequest request) {

		user.setName(name);
		user.setPhone(phone);
		user.setDesc(desc);
		user.setCity(city);
		
		HibernateManager.getInstance().updateEntity(user);
		
		response.setMeta("Profile updated successfully");
		response.setType(ResponseType.SUCCESS);
		
	}

}
